import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.Scanner;

public class Demo2 {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            MysqlDataSource mysqlDataSource = new MysqlDataSource();
            mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/java113");
            mysqlDataSource.setUser("root");
            mysqlDataSource.setPassword("gjm041027");

            DataSource dataSource = mysqlDataSource;

            connection = dataSource.getConnection();

            String sql = "select student_id, sn, name, mail, class_id from student where name = ?";
            preparedStatement = connection.prepareStatement(sql);

            Scanner scanner = new Scanner(System.in);
            String name0 = scanner.nextLine();

            preparedStatement.setString(1, name0);

            resultSet = preparedStatement.executeQuery();

            while (resultSet.next()) {
                Long student_id = (Long)resultSet.getLong("student_id");
                String sn = resultSet.getString("sn");
                String name = resultSet.getString("name");
                String mail = resultSet.getString("mail");
                Long class_id = (Long)resultSet.getLong("class_id");
                System.out.println(MessageFormat.format("student_id = {0}, sn = {1}, name = {2}, mail = {3}, class_id = {4}",
                        student_id, sn, name, mail, class_id));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
